package com.panfeng.xcloud.scheduler.util;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Day;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.AttributedString;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

public class LineChartUtil {

    public static void drawDualLineChart(String fileName, String chartTitle, String xAxisLabel,
                                         List<ZonedDateTime> xData, List<Double> yData1, List<Double> yData2) throws InvocationTargetException, InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() {
                try {
                    JFreeChart chart = createDualLineChart(chartTitle, xAxisLabel, xData, yData1, yData2);
                    displayChart(chart, chartTitle, fileName + ".png");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 通知测试线程异步任务完成
                    latch.countDown();
                }
                return null;
            }
        };
        worker.execute();
        latch.await();
    }

    private static JFreeChart createDualLineChart(String chartTitle, String xAxisLabel,
                                                  List<ZonedDateTime> xData, List<Double> yData1, List<Double> yData2) {
        // 将ZonedDateTime按照时间顺序排序
        List<ZonedDateTime> sortedXData = xData.stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        TimeSeries series1 = createSeries(sortedXData, yData1);
        TimeSeriesCollection dataset1 = new TimeSeriesCollection(series1);

        TimeSeries series2 = createSeries(sortedXData, yData2);
        TimeSeriesCollection dataset2 = new TimeSeriesCollection(series2);

        String yAxisLabel = "胜率";
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
                chartTitle,
                xAxisLabel,
                yAxisLabel,
                dataset1,  // 使用第一个数据集
                false,
                true,
                false
        );

        Font chartTitleFont = new Font("宋体", Font.BOLD, 18);
        chart.getTitle().setFont(chartTitleFont);

        XYPlot plot = chart.getXYPlot();
        DateAxis dateAxis = new DateAxis(xAxisLabel);
        // 设置日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateAxis.setDateFormatOverride(dateFormat);
        plot.setDomainAxis(dateAxis);

        NumberAxis valueAxisLeft = new NumberAxis(yAxisLabel);
        plot.setRangeAxis(valueAxisLeft);
        XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer(true, false);
        plot.setRenderer(renderer1);

        // 设置左边纵坐标轴颜色
        valueAxisLeft.setTickLabelPaint(Color.BLUE);
        valueAxisLeft.setLabelPaint(Color.BLUE);
        Font fontLeft = new Font("SansSerif", Font.BOLD, 16); // 设置字体
        valueAxisLeft.setTickLabelFont(fontLeft);
        valueAxisLeft.setLabelFont(fontLeft);

        // 添加第二个数据集和纵坐标轴
        plot.setDataset(1, dataset2);
        NumberAxis valueAxisRight = new NumberAxis("当前可用资金");  // 右边的纵坐标轴
        plot.setRangeAxis(1, valueAxisRight);
        plot.mapDatasetToRangeAxis(1, 1);

        XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true, false);
        plot.setRenderer(1, renderer2);

        // 设置右边纵坐标轴颜色
        valueAxisRight.setTickLabelPaint(Color.RED);
        valueAxisRight.setLabelPaint(Color.RED);
        Font fontRight = new Font("SansSerif", Font.BOLD, 16); // 设置字体
        valueAxisRight.setTickLabelFont(fontRight);
        valueAxisRight.setLabelFont(fontRight);

        return chart;
    }

    private static TimeSeries createSeries(List<ZonedDateTime> xData, List<Double> yData) {
        TimeSeries series = new TimeSeries("Data Series");

        for (int i = 0; i < xData.size(); i++) {
            Date date = Date.from(xData.get(i).toInstant());
            series.addOrUpdate(new Day(date), yData.get(i));
        }

        return series;
    }

    private static void displayChart(JFreeChart chart, String chartTitle, String fileName) {
        //JFrame frame = new JFrame(chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);

        /*frame.setLayout(new GridLayout(1, 1));
        frame.add(chartPanel);
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);*/
        chartPanel.setSize(800, 600);
        // 保存图表为PNG图片
        saveChartAsPNG(chartPanel, "quantData/" + fileName);
    }

    private static void saveChartAsPNG(ChartPanel chartPanel, String fileName) {
        BufferedImage image = new BufferedImage(chartPanel.getWidth(), chartPanel.getHeight(), BufferedImage.TYPE_INT_ARGB);
        chartPanel.paint(image.getGraphics());

        try {
            ImageIO.write(image, "png", new File(fileName));
            System.out.println("图表保存为 " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
